package org.groovyflow.db;

import java.util.ArrayList;
import java.util.List;

public class ActiveRecordHelp {
	
	/**
	 * Creates a string that looks like this:
	 * update product set price = ?, description = ? where id = ?
	 * or
	 * update product set price = ?, description = ? where id = ? and version = ?
	 */
	public String makeUpdateStatement(List columnNamesNotIncludingId, ActiveRecord rec){
		StringBuffer buf = new StringBuffer();
		buf.append("update ").append(rec.gTableName()).append(" set ");
		for(int i = 0, m = columnNamesNotIncludingId.size(); i < m; i++){
			buf.append(columnNamesNotIncludingId.get(i) + " = ?");
			if(i < m - 1){
				buf.append(", ");
			}
		}
		buf.append(" where ").append(rec.gIdName()).append(" = ?");
		String versionField  = rec.gVersionFieldName();
		if(versionField != null){
			buf.append(" and ").append(versionField).append(" = ?");
		}
		return buf.toString();
	}

	/**
	 * Creates a String that looks like this:
	 * insert into product(id, price, description) values(?, ?, ?)
	 */
	public String makeInsertStatement(List columnNamesNotIncludingId, ActiveRecord rec) {
		StringBuffer buf = new StringBuffer();
		buf.append("insert into ").append(rec.gTableName()).append("(");
		buf.append(rec.gIdName()).append(", ");
		for(int i = 0, m = columnNamesNotIncludingId.size(); i < m; i++){
			buf.append(columnNamesNotIncludingId.get(i));
			if(i < m - 1){
				buf.append(", ");
			}
			else
				buf.append(")");
		}
		buf.append(" values(?, ");
		for(int i = 0, m = columnNamesNotIncludingId.size(); i < m; i++){
			buf.append("?");
			if(i < m - 1){
				buf.append(", ");
			}
			else
				buf.append(")");
		}		
		return buf.toString();
	}
	
	public static void main(String[] args){
		ActiveRecord willBeAbstract = new ActiveRecord();
		ActiveRecordHelp help = new ActiveRecordHelp();
		List columnNames = new ArrayList();
		columnNames.add("price");
		columnNames.add("description");
		String update = help.makeUpdateStatement(columnNames, willBeAbstract);
		System.out.println(update);
		String insert = help.makeInsertStatement(columnNames, willBeAbstract);
		System.out.println(insert);
		
	}

}
